package com.woniuxy.rms.service.impl;

import com.woniuxy.rms.dao.*;
import com.woniuxy.rms.pojo.*;
import com.woniuxy.rms.service.ServerService;
import com.woniuxy.rms.util.*;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Auther: ChenGang  <br/>
 * Date: 2020/3/27 0027:上午 11:46  <br/>
 * Description:服务的服务实现类
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ServerServiceImpl implements ServerService {

    @Autowired
    ServerMenuMapper serverMenuMapper;

    @Autowired
    VendorMapper vendorMapper;

    @Autowired
    PropertyMapper propertyMapper;

    @Autowired
    ServersMapper serversMapper;

    @Autowired
    RolesMapper rolesMapper;

    @Autowired
    ServerCommentsMapper serverCommentsMapper;

    @Autowired
    ServerTagsMapper serverTagsMapper;

    @Autowired
    ServerSubscribeMapper serverSubscribeMapper;

    @Autowired
    ServerOrdersMapper serverOrdersMapper;

    @Override
    public List<ServerMenu> findAll() {
        return serverMenuMapper.findAll();
    }

    @Override
    public DataResult saveMenu(ServerMenu serverMenu) {
        //查询服务
        List<ServerMenu> serverMenu1 = serverMenuMapper.findByName(serverMenu.getServerName());
        for (ServerMenu menu : serverMenu1) {
            if (serverMenu.getParentId().equals(menu.getParentId())){
                return DataResult.failed("服务名重复，添加失败！");
            }
        }
        //添加创建时间
        serverMenu.setCreateTime(new Date());
        //添加创建人账户
        Admins admins = (Admins) SecurityUtils.getSubject().getPrincipal();
        serverMenu.setCreator(admins.getAccount());
        //确定审核状态，超级管理员和服务管理员不需要审核
        //查询角色
        Roles roles = rolesMapper.selectByPrimaryKey(admins.getRoleId());
        if (roles.getRole().equals(ServerCheckUtil.ADMIN.getRole()) ||
                roles.getRole().equals(ServerCheckUtil.SERVERADMIN.getRole())){
            serverMenu.setStatus(1);
        }else {
            serverMenu.setStatus(0);
        }
        serverMenuMapper.insertSelective(serverMenu);
        return DataResult.success();
    }

    @Override
    public ServerMenu findById(Long id) {
        return serverMenuMapper.findById(id);
    }

    @Override
    public DataResult updateMenu(ServerMenu serverMenu) {
        //查询服务
        List<ServerMenu> serverMenu1 = serverMenuMapper.findByName(serverMenu.getServerName());
        for (ServerMenu menu : serverMenu1) {
            if (serverMenu.getParentId().equals(menu.getParentId())){
                if (!serverMenu.getId().equals(menu.getId())) {
                    return DataResult.failed("服务名重复，添加失败！");
                }

            }
        }
        //更新时间
        serverMenu.setUpdateTime(new Date());
        serverMenuMapper.updateByPrimaryKeySelective(serverMenu);
        return DataResult.success();
    }

    @Override
    public DataResult batchDel(String ids) {
        List<Long> menuIds = Arrays.stream(ids.split(",")).map(s -> Long.parseLong(s)).collect(Collectors.toList());
        List<Long> perentIds = serverMenuMapper.findPerentId(menuIds);
        //根服务节点不能直接删除
        if (perentIds.size() > 0) {
            return DataResult.failed("根服务不能直接删除，请先删除子服务！");
        }
        //判断该服务是否被分配
        List<Servers> servers = serversMapper.findByMenuIds(menuIds);
        if (servers.size() > 0){
            return DataResult.failed("服务已经有商家或物业入驻，不能删除！");
        }
        serverMenuMapper.batchDel(menuIds);
        return DataResult.success();
    }

    @Override
    public DataResult checkMenu(Long id, Integer status) {
        serverMenuMapper.updateStatus(id,status,new Date());
        return DataResult.success();
    }

    @Override
    public List<Servers> findByPage(Integer currentPage, Integer pageSize) {
        //查询商户入驻信息
        List<Servers> byPage = serversMapper.findVentorByPage(currentPage, pageSize, ServerTypeUtil.VENTOR.getServerType());
        //查询物业入驻信息
        List<Servers> proByPage = serversMapper.findProByPage(currentPage, pageSize, ServerTypeUtil.PROPERTY.getServerType());
        byPage.addAll(proByPage);//结合在一起
        return byPage;
    }


    @Override
    public DataResult checkStatus(Long id, Integer status) {
        serversMapper.checkStatus(id,status,new Date());
        //判断是商户还是物业(发送邮件)
        Servers servers = serversMapper.selectByPrimaryKey(id);
        try {
            //商户
            if (servers.getServerType().equals(ServerTypeUtil.VENTOR.getServerType())){
                Vendor vendor = vendorMapper.selectByPrimaryKey(servers.getSupplierId());
                //入驻认证通过
                if (status.equals(CheckUtil.PASS)){
                    EmailUtil.sendMail(vendor.getEmail(),"尊敬的商家用户您好！您的入驻申请已通过！非常感谢您的入驻！");
                //入驻不通过
                }else {
                    EmailUtil.sendMail(vendor.getEmail(),"尊敬的商家用户您好！非常抱歉，由于部分原因，您的入驻资格已被取消！");

                }
            }
            //物业
            if (servers.getServerType().equals(ServerTypeUtil.PROPERTY.getServerType())){
                Property property = propertyMapper.selectByPrimaryKey(servers.getSupplierId());
                //入驻通过
                if (status.equals(CheckUtil.PASS)){
                    EmailUtil.sendMail(property.getEmail(),"尊敬的物业用户您好！您的入驻申请已通过！非常感谢您的入驻！");
                //入驻不通过
                }else {
                    EmailUtil.sendMail(property.getEmail(),"尊敬的物业用户您好！非常抱歉，由于部分原因，您的入驻资格已被取消！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DataResult.success();
    }

    @Override
    public DataResult batchDelEnter(String ids) {
        List<Long> serverIds = Arrays.stream(ids.split(",")).map(s -> Long.parseLong(s)).collect(Collectors.toList());
        //删除所有订单
        //判断是否有已支付未完成的订单
        List<ServerOrders> orders = serverOrdersMapper.findByServerIds(serverIds);
        if (orders.size() > 0){
            return DataResult.failed("有未完成交易，不能删除！");
        }
        //删除所有订单
        serverOrdersMapper.deleteByServerIds(serverIds);
        //删除所有评论
        serverCommentsMapper.deleteByServerIds(serverIds);
        //删除所有点赞
        serverTagsMapper.deleteByServerIds(serverIds);
        //删除所有预约
        serverSubscribeMapper.deleteByServerIds(serverIds);
        //删除入驻信息
        serversMapper.batchDelEnter(serverIds);
        return DataResult.success();
    }
}